package service

import (
	"errors"
	"fmt"
	"im/model"
	"im/util"
	"math/rand"
	"time"
)

type UserService struct {
}

// 注册
func (u *UserService) Register(
    mobile,
    plainpwd,
    nickname,
    avatar,
    sex string) (user model.User, err error) {
    // 检测手机是否注册
    _, err = DbEng.Where("mobile=?", mobile).Get(&user)
    if err != nil {
        return user, err
    }
    if user.Id > 0 {
        return user, errors.New("该手机号已经注册")
    }
    // fmt.Println(plainpwd)
    user.Mobile = mobile
    user.Avatar = avatar
    user.Nickname = nickname
    user.Sex = sex
    user.Salt = fmt.Sprintf("%06d", rand.Int31n(1000000))
    user.Passwd = util.MakePassword(plainpwd, user.Salt)
    user.CreateTime = time.Now()
    user.Token = fmt.Sprintf("%08d", rand.Int31n(100000000))
    _, err = DbEng.InsertOne(&user)
    return user, err
}

// 登录 
func (u *UserService) Login(
    mobile,
    plainpwd string) (user model.User, err error) {
    DbEng.Where("mobile=?", mobile).Get(&user)
    // fmt.Println(user)
    if user.Id == 0 {
        return user, errors.New("没有该用户")
    }
    // 比对密码
    if util.ValidatePassword(plainpwd, user.Salt, user.Passwd) {
       return user, errors.New("密码不正确") 
    }
    // 刷新token
    user.Token = util.Md5Encode(fmt.Sprintf("%d", time.Now().Unix()))
    DbEng.ID(user.Id).Cols("token").Update(&user)
    return user, nil
}

// 根据指定id查找用户
func (u *UserService) Find(id int64) (user model.User) {
    DbEng.ID(id).Get(&user)
    return user
}
